package com.fzl.spring_chatroom.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fzl.spring_chatroom.service.MessageSessionService;
import com.fzl.spring_chatroom.service.UserService;
import com.fzl.spring_chatroom.model.dao.Friend;
import com.fzl.spring_chatroom.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLOutput;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.Map;
import com.fzl.spring_chatroom.service.MessageService;

@Component
public class WebSocketController extends TextWebSocketHandler {
    @Autowired
    private MessageSessionService messageSessionService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    // userId -> session
    private static final ConcurrentHashMap<Integer, WebSocketSession> userSessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从参数token获取userId
        String token = getTokenFromSession(session);
        Claims claims = JwtUtils.parseToken(token);
        if (claims != null && claims.get("id") != null) {
            Integer userId = Integer.valueOf(claims.get("id").toString());
            if (userSessionMap.get(userId) != null) {
                System.out.println("【" + userId + "】已经在其它设备登录，请勿重新登陆");
                return;
            }
            userSessionMap.put(userId, session);
            session.getAttributes().put("userId", userId);
            System.out.println("连接成功: userId=" + userId);
        } else {
            session.close();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 解析消息
        JSONObject json = JSON.parseObject(message.getPayload());
        String type = json.getString("type");
        if ("message".equals(type)) {
            Integer sessionId = json.getIntValue("sessionId");
            String content = json.getString("content");
            Integer fromId = (Integer) session.getAttributes().get("userId");
            String fromName = userService.getUser(fromId).getUsername();
            // 写入数据库
            messageService.addMessage(sessionId, fromId, fromName, content);
            // 获取会话成员
            List<Friend> members = messageSessionService.getFriendsBySessionId(sessionId, fromId);
            // 构造响应
            JSONObject resp = new JSONObject();
            resp.put("type", "message");
            resp.put("fromId", fromId);
            resp.put("fromName", fromName);
            resp.put("sessionId", sessionId);
            resp.put("content", content);
            // 推送给所有成员
            for (Friend member : members) {
                WebSocketSession memberSession = userSessionMap.get(member.getFriendId());
                if (memberSession != null && memberSession.isOpen()) {
                    memberSession.sendMessage(new TextMessage(resp.toJSONString()));
                }
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("异常" + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Integer userId = (Integer) session.getAttributes().get("userId");
        if (userId != null) {
            userSessionMap.remove(userId);
            System.out.println("下线: userId=" + userId);
        }
    }

    // 辅助方法：从url参数获取token
    private String getTokenFromSession(WebSocketSession session) {
        String uri = session.getUri().toString();
        String[] parts = uri.split("[?&]");
        for (String part : parts) {
            if (part.startsWith("token=")) {
                return part.substring(6);
            }
        }
        return null;
    }

    // 新增：推送好友请求
    public static void sendFriendRequest(Integer toUserId, Object payload) {
        WebSocketSession session = userSessionMap.get(toUserId);
        if (session != null && session.isOpen()) {
            try {
                JSONObject resp = new JSONObject();
                resp.put("type", "friendRequest");
                resp.put("data", payload);
                session.sendMessage(new TextMessage(resp.toJSONString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 新增：推送好友同意
    public static void sendFriendAccept(Integer toUserId, Object payload) {
        WebSocketSession session = userSessionMap.get(toUserId);
        if (session != null && session.isOpen()) {
            try {
                JSONObject resp = new JSONObject();
                resp.put("type", "friendAccept");
                resp.put("data", payload);
                session.sendMessage(new TextMessage(resp.toJSONString()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
